package com.duoduo.springboot.security.core;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import com.duoduo.springboot.security.model.Role;
import com.duoduo.springboot.security.model.User;

public class SecurityUser extends User implements UserDetails {
	private static final long serialVersionUID = 1849727307624022482L;
	private List<Role> userRoles = new ArrayList<Role>(0);

	public SecurityUser(User user, List<Role> userRoles) {
		if (user != null) {
			this.setId(user.getId());
			this.setName(user.getName());
			this.setPassword(user.getPassword());
		}

		if (!CollectionUtils.isEmpty(userRoles)) {
			this.setUserRoles(userRoles);
		}
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Collection<GrantedAuthority> authorities = new ArrayList<>();
		if (!CollectionUtils.isEmpty(userRoles)) {
			for (Role role : userRoles) {
				SimpleGrantedAuthority authority = new SimpleGrantedAuthority("" + role.getId());
				authorities.add(authority);
			}
		}
		return authorities;
	}

	@Override
	public String getPassword() {
		return super.getPassword();
	}

	@Override
	public String getUsername() {
		return super.getName();
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

	public List<Role> getUserRoles() {
		return userRoles;
	}

	public void setUserRoles(List<Role> userRoles) {
		this.userRoles = userRoles;
	}
}
